<?php

namespace app\api\controller\gifts;
use app\api\controller\Controller;
use app\api\model\gifts\Gifts as GiftsModel;
use app\api\model\gifts\Order as OrderModel;
use app\api\model\gifts\GiftsOrderGoods as GiftsOrderGoodsModel;
use app\api\service\gifts\PaySuccess;
use app\api\service\Payment as PaymentService;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\service\qrcode\Gifts as GiftsPoster;
use app\api\model\dealer\Referee as RefereeModel;
use think\Request;
use think\Db;

/**
 * 爆品礼管理控制器
 * Class Gifts
 * @package app\store\controller
 */
class Gifts extends Controller
{

    /* @var \app\api\model\User $model */
    protected $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();

    }

    /**
     * 首页爆品礼列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function buyList()
    {
        $param = Request::instance()->param();
        // 获取全部列表
        $model = new GiftsModel;
        //获取用户的
        $list = $model->buyList($param,$this->getUser(false));
        return $this->renderSuccess($list);
    }


    /**
     * 微股客爆品礼列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function keList()
    {
        $param = Request::instance()->param();
        // 获取全部列表
        $model = new GiftsModel;
        //获取用户的
        $list = $model->keList($param,$this->getUser(false));
        return $this->renderSuccess($list);
    }


    /**
     * 爆品礼详情
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function giftsDetail()
    {
        $param = Request::instance()->param();


//        //上级id
//        $refereeId = isset($param['superior_user_id']) ? $param['superior_user_id'] : null;
//
//        // 记录推荐人关系
//        if ($this->user && $refereeId > 0) {
//            //是否已存在推荐关系
//            if (!RefereeModel::isExistReferee($this->user['user_id'])) {
//                RefereeModel::createRelation($this->user['user_id'], $refereeId);
//            }
//        }

        $model = GiftsModel::apiDetail($param['gifts_id']);
        if(empty($model)){
            return $this->renderError('爆品礼不存在，请刷新后重试');
        }
        
        $count=Db::name('meizhuang_comment')->where(['wxapp_id'=>$param['wxapp_id']])->count();
        $storeInfo=Db::name('store_shop')->where(['wxapp_id'=>$param['wxapp_id']])->find();
        $tx=Db::name('upload_file')->where(['file_id'=>$storeInfo['logo_image_id']])->find();
        $imgeurl=$tx['file_url'].'/'.$tx['file_name'];
        $model['imageUrl']=$imgeurl;
        $model['commentCount']=$count;

        $model['gifts_content'] = htmlspecialchars_decode($model['gifts_content']);

        $model['superior_user_id'] = $this->user['user_id'];

        return $this->renderSuccess($model);

    }


    /**
     * 爆品礼购买
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function submit()
    {
        $param = Request::instance()->param();
        // 用户信息
        $userInfo = $this->getUser();

        // 生成充值订单
        $model = new OrderModel;
        if (!$model->createOrder($this->user, $param['gifts_id'],$param['superior_user_id'])) {
            return $this->renderError($model->getError() ?: '生成订单失败');
        }

        //获取订单爆品礼详情
        $giftOrder = GiftsOrderGoodsModel::detail(['order_id'=>$model['order_id']]);

        // 获取订单详情
        $PaySuccess = new PaySuccess($model['order_no']);
        //免费爆品礼
        if($giftOrder['gifts_type']==10){
            $status = $PaySuccess->paySuccess(10);
            $message = ['success' => '支付成功', 'error' => '订单已支付'];
            if($status){
                return $this->renderSuccess([],$message);
            }
        }
        //支付价格小于0
        if($model['pay_price']<=0 && $giftOrder['gifts_type']==20){
            return $this->renderError('支付金额错误');
        }
        // 构建微信支付
        $payment = PaymentService::wechat(
            $userInfo,
            $model['order_id'],
            $model['order_no'],
            $model['pay_price'],
            OrderTypeEnum::GIFTSPAY
        );
        // 充值状态提醒
        $message = ['success' => '下单成功', 'error' => '订单未支付'];
        return $this->renderSuccess(compact('payment', 'message'), $message);
    }

    /**
     * 生成商品海报
     * @param $gifts_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function poster(){

        $param = Request::instance()->param();

        //商品详情
        $detail = GiftsModel::apiDetail($param['gifts_id']);
        $Qrcode = new GiftsPoster($detail, $this->getUser());
        return $this->renderSuccess([
            'qrcode' => $Qrcode->getImage(),
            'code'=>1
        ],'生成成功');

    }

}



